<template>
  <div class="register-container">
    <div class="register-box">
      <!-- 返回登录 -->
      <div class="back-login">
        <el-button type="text" @click="goToLogin">
          <iconify-icon icon="mdi:arrow-left" width="20" height="20"></iconify-icon>
          返回登录
        </el-button>
      </div>

      <div class="register-header">
        <h2>用户注册</h2>
        <p>User Register</p>
      </div>

      <!-- 用户类型选择 -->
      <div class="user-type-selection">
        <h3>选择用户类型</h3>
        <div class="user-type-grid">
          <div
            v-for="userType in userTypes"
            :key="userType.type"
            :class="['user-type-card', { active: selectedType === userType.type }]"
            @click="selectUserType(userType.type)"
          >
            <iconify-icon :icon="userType.icon" width="32" height="32" :style="{ color: userType.color }"></iconify-icon>
            <span>{{ userType.name }}</span>
          </div>
        </div>
      </div>

      <!-- 注册表单 -->
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
        @submit.prevent="handleRegister"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            :placeholder="getUsernamePlaceholder()"
            prefix-icon="User"
            size="large"
            clearable
            @blur="checkUsernameExist"
          />
        </el-form-item>

        <el-form-item prop="realName">
          <el-input
            v-model="registerForm.realName"
            placeholder="请输入真实姓名"
            prefix-icon="UserFilled"
            size="large"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            size="large"
            show-password
            clearable
            @keyup.enter="handleRegister"
          />
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            prefix-icon="Lock"
            size="large"
            show-password
            clearable
            @keyup.enter="handleRegister"
          />
        </el-form-item>

        <el-form-item prop="inviteCode">
          <el-input
            v-model="registerForm.inviteCode"
            placeholder="请输入管理员邀请码"
            prefix-icon="Key"
            size="large"
            clearable
            show-password
          >
            <template #append>
              <el-button type="info" @click="showInviteCodeHelp">
                <iconify-icon icon="mdi:help-circle" width="16" height="16"></iconify-icon>
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="studentId" v-if="showStudentId">
          <el-input
            v-model="registerForm.studentId"
            placeholder="请输入学号/工号（选填）"
            prefix-icon="Card"
            size="large"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <div class="register-agreement">
            <el-checkbox v-model="registerForm.agreement">
                我已阅读并同意
                <el-link type="primary" @click="showUserAgreement">《用户协议》</el-link>
                和
                <el-link type="primary" @click="showPrivacyPolicy">《隐私政策》</el-link>
            </el-checkbox>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="register-button"
            :loading="loading"
            :disabled="!selectedType || !registerForm.agreement"
            @click="handleRegister"
          >
            {{ loading ? '注册中...' : '注册' }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 用户协议对话框 -->
      <el-dialog
        v-model="agreementVisible"
        title="用户协议"
        width="50%"
        :before-close="closeAgreement"
      >
        <div class="agreement-content">
          <h3>校园运动会管理系统用户协议</h3>
          <p>欢迎使用校园运动会管理系统。请仔细阅读以下条款：</p>
          <ol>
            <li>用户应当提供真实、准确的注册信息</li>
            <li>用户有责任保护自己的账号安全</li>
            <li>用户应当遵守学校相关规定和系统使用规范</li>
            <li>系统有权对违规用户进行处理</li>
            <li>本协议的解释权归系统管理员所有</li>
          </ol>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeAgreement">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 隐私政策对话框 -->
      <el-dialog
        v-model="privacyVisible"
        title="隐私政策"
        width="50%"
        :before-close="closePrivacy"
      >
        <div class="privacy-content">
          <h3>校园运动会管理系统隐私政策</h3>
          <p>我们重视您的隐私保护，以下是我们的隐私政策：</p>
          <ol>
            <li>我们收集的信息仅用于系统功能实现</li>
            <li>未经用户同意，不会向第三方泄露个人信息</li>
            <li>用户可以查询、修改自己的个人信息</li>
            <li>我们采取安全措施保护用户数据</li>
            <li>如有隐私问题，请联系系统管理员</li>
          </ol>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closePrivacy">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 邀请码帮助对话框 -->
      <el-dialog
        v-model="inviteCodeHelpVisible"
        title="邀请码说明"
        width="50%"
        :before-close="closeInviteCodeHelp"
      >
        <div class="invite-code-help-content">
          <h3>管理员邀请码</h3>
          <p>为保障系统安全，新用户注册需要管理员邀请码：</p>
          <div class="invite-code-info">
            <el-alert
              title="测试邀请码"
              type="info"
              :closable="false"
              show-icon
            >
              <p>运动员注册：<code>SCHOOL2024</code></p>
              <p>志愿者注册：<code>VOLUNTEER2024</code></p>
              <p>教师注册：<code>TEACHER2024</code></p>
              <p>裁判注册：<code>REFEREE2024</code></p>
            </el-alert>
          </div>
          <div class="invite-code-note">
            <p><strong>注意：</strong></p>
            <ul>
              <li>邀请码由系统管理员分发</li>
              <li>不同用户类型使用不同的邀请码</li>
              <li>邀请码有有效期限制</li>
              <li>如有疑问请联系系统管理员</li>
            </ul>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeInviteCodeHelp">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { register, checkUsername } from '@/api/auth'

export default {
  name: 'RegisterPage',
  setup() {
    const router = useRouter()

    // 表单引用
    const registerFormRef = ref(null)
    const loading = ref(false)
    const selectedType = ref('')
    const agreementVisible = ref(false)
    const privacyVisible = ref(false)
    const inviteCodeHelpVisible = ref(false)

    // 用户类型配置
    const userTypes = [
      { type: 'player', name: '运动员', icon: 'mdi:run', color: '#3b82f6' },
      { type: 'volunteer', name: '志愿者', icon: 'mdi:account-student', color: '#2563eb' },
      { type: 'teacher', name: '教师', icon: 'mdi:account-tie', color: '#f97316' },
      { type: 'referee', name: '裁判', icon: 'mdi:whistle', color: '#22c55e' }
    ]

    // 注册表单数据
    const registerForm = reactive({
      username: '',
      realName: '',
      password: '',
      confirmPassword: '',
      inviteCode: '',
      studentId: '',
      userType: '',
      agreement: false
    })

    // 是否显示学号/工号输入框
    const showStudentId = computed(() => {
      return ['player', 'teacher'].includes(selectedType.value)
    })

    // 验证邀请码格式
    const validateInviteCodeFormat = (code) => {
      // 简单的邀请码格式验证：至少6位字符，包含字母和数字
      return /^[A-Za-z0-9]{6,}$/.test(code)
    }

    // 密码验证器
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value.length < 6) {
        callback(new Error('密码长度不能少于6位'))
      } else if (!/(?=.*[a-zA-Z])(?=.*\d)/.test(value)) {
        callback(new Error('密码必须包含字母和数字'))
      } else {
        if (registerForm.confirmPassword !== '') {
          registerFormRef.value?.validateField('confirmPassword')
        }
        callback()
      }
    }

    // 确认密码验证器
    const validateConfirmPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== registerForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }

    // 用户名验证器
    const validateUsername = async (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else if (value.length < 3) {
        callback(new Error('用户名长度不能少于3位'))
      } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
        callback(new Error('用户名只能包含字母、数字和下划线'))
      } else {
        try {
          const response = await checkUsername(value)
          if (response.data.exists) {
            callback(new Error('该用户名已被注册'))
          } else {
            callback()
          }
        } catch (error) {
          callback(new Error('验证用户名时发生错误'))
        }
      }
    }

    // 邀请码验证器
    const validateInviteCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入邀请码'))
      } else if (!validateInviteCodeFormat(value)) {
        callback(new Error('邀请码格式不正确'))
      } else {
        callback()
      }
    }

    // 表单验证规则
    const registerRules = {
      username: [
        { required: true, validator: validateUsername, trigger: 'blur' }
      ],
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, validator: validatePass, trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, validator: validateConfirmPass, trigger: 'blur' }
      ],
      inviteCode: [
        { required: true, validator: validateInviteCode, trigger: 'blur' }
      ]
    }

    // 选择用户类型
    const selectUserType = (type) => {
      selectedType.value = type
      registerForm.userType = type
      // 清空表单
      registerForm.username = ''
      registerForm.realName = ''
      registerForm.password = ''
      registerForm.confirmPassword = ''
      registerForm.inviteCode = ''
      registerForm.studentId = ''
    }

    // 获取用户名占位符
    const getUsernamePlaceholder = () => {
      if (!selectedType.value) return '请先选择用户类型'
      const typeConfig = userTypes.find(t => t.type === selectedType.value)
      return `请输入${typeConfig?.name || '用户'}用户名`
    }

    // 检查用户名是否存在
    const checkUsernameExist = async () => {
      if (!registerForm.username || registerForm.username.length < 3) return

      try {
        const response = await checkUsername(registerForm.username)
        if (response.data.exists) {
          ElMessage.warning('该用户名已被注册')
        }
      } catch (error) {
        console.error('检查用户名失败:', error)
      }
    }

    // 显示邀请码帮助
    const showInviteCodeHelp = () => {
      inviteCodeHelpVisible.value = true
    }

    // 处理注册
    const handleRegister = async () => {
      if (!selectedType.value) {
        ElMessage.warning('请先选择用户类型')
        return
      }

      if (!registerFormRef.value) return

      try {
        // 表单验证
        await registerFormRef.value.validate()

        loading.value = true

        // 准备注册数据
        const registerData = {
          username: registerForm.username,
          realName: registerForm.realName,
          password: registerForm.password,
          userType: registerForm.userType,
          inviteCode: registerForm.inviteCode
        }

        // 如果是学生或教师，添加学号/工号
        if (showStudentId.value && registerForm.studentId) {
          registerData.studentId = registerForm.studentId
        }

        // 调用注册接口
        await register(registerData)

        ElMessage.success('注册成功！请登录')

        // 跳转到登录页面
        router.push('/login')

      } catch (error) {
        console.error('注册失败:', error)
        ElMessage.error(error.response?.data?.message || '注册失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    // 返回登录页面
    const goToLogin = () => {
      router.push('/login')
    }

    // 显示用户协议
    const showUserAgreement = () => {
      agreementVisible.value = true
    }

    // 显示隐私政策
    const showPrivacyPolicy = () => {
      privacyVisible.value = true
    }

    // 关闭用户协议
    const closeAgreement = () => {
      agreementVisible.value = false
    }

    // 关闭隐私政策
    const closePrivacy = () => {
      privacyVisible.value = false
    }

    // 关闭邀请码帮助
    const closeInviteCodeHelp = () => {
      inviteCodeHelpVisible.value = false
    }

    return {
      registerFormRef,
      registerForm,
      registerRules,
      loading,
      selectedType,
      userTypes,
      showStudentId,
      agreementVisible,
      privacyVisible,
      inviteCodeHelpVisible,
      selectUserType,
      getUsernamePlaceholder,
      checkUsernameExist,
      showInviteCodeHelp,
      handleRegister,
      goToLogin,
      showUserAgreement,
      showPrivacyPolicy,
      closeAgreement,
      closePrivacy,
      closeInviteCodeHelp
    }
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.register-box {
  background: white;
  border-radius: 16px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 500px;
  backdrop-filter: blur(10px);
  position: relative;
}

.back-login {
  position: absolute;
  top: 20px;
  left: 20px;
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
  margin-top: 20px;
}

.register-header h2 {
  color: #333;
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 8px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.register-header p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.user-type-selection {
  margin-bottom: 30px;
}

.user-type-selection h3 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
  font-size: 16px;
  font-weight: 500;
}

.user-type-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
  gap: 12px;
}

.user-type-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px 10px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f9fafb;
}

.user-type-card:hover {
  border-color: #667eea;
  background: #f3f4f6;
  transform: translateY(-2px);
}

.user-type-card.active {
  border-color: #667eea;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

.user-type-card span {
  margin-top: 8px;
  font-size: 12px;
  color: #374151;
  font-weight: 500;
}

.register-form {
  margin-bottom: 20px;
}

.register-agreement {
  font-size: 14px;
  line-height: 1.5;
}

.register-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  border: none;
  transition: all 0.3s ease;
}

.register-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.register-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.agreement-content, .privacy-content {
  padding: 20px;
  max-height: 400px;
  overflow-y: auto;
  line-height: 1.8;
}

.agreement-content h3, .privacy-content h3 {
  color: #333;
  margin-bottom: 15px;
  text-align: center;
}

.agreement-content ol, .privacy-content ol {
  padding-left: 20px;
}

.agreement-content li, .privacy-content li {
  margin-bottom: 10px;
  color: #666;
}

.invite-code-help-content {
  padding: 20px;
  max-height: 400px;
  overflow-y: auto;
  line-height: 1.8;
}

.invite-code-help-content h3 {
  color: #333;
  margin-bottom: 15px;
  text-align: center;
}

.invite-code-info {
  margin: 20px 0;
}

.invite-code-info code {
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-weight: bold;
  color: #e6a23c;
}

.invite-code-note {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.invite-code-note ul {
  margin: 10px 0;
  padding-left: 20px;
}

.invite-code-note li {
  margin-bottom: 5px;
  color: #666;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  padding: 0 15px;
  box-shadow: 0 0 0 1px #e4e7ed inset;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #667eea inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #667eea inset;
}

:deep(.el-form-item__error) {
  font-size: 12px;
  color: #f56c6c;
}

:deep(.el-checkbox__label) {
  font-size: 14px;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .register-box {
    padding: 30px 20px;
  }

  .register-header h2 {
    font-size: 24px;
  }

  .user-type-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>